package states;

import hypeerweb.Node;
import hypeerweb.Range;

/**
 * The Up pointing state, where we look for a larger up pointer,
 * or a smaller, childless neighbor.
 *
 * @author brinkerhoff_kendra
 *
 */
public class UpPointingNodeState extends NodeState {

	/**
	 * Default constructor, sets the current state of the machine.
	 */
	public UpPointingNodeState() {
		STATE_ID = 1;
	}

	/**
	 * Determines if range.upperBound has an up pointer with a larger webid than range.lowerBound. 
	 * 
	 * @pre range &ne; null
	 * @post result = DownPointingNodeState where lowerBound' = upperBound.largestUpPointer and lowerBound'.id > lowerBound.id
	 * 		<br>OR
	 * 		<br>result = StandardNodeState if upperBound has no up pointers larger than lowerBound
	 * 		<br>OR
	 * 		<br>result = TerminalNodeState if lowerBound.parent.id + 1 == upperBound.id
	 */
	public final NodeState shrinkRange(final Range r) {
		range = r;

		if (range.getRange() == 1) {
			return new TerminalNodeState();
		}

		Node upper = range.getUpperBound();

		Node lower = upper.getConnections().getLargestUpPointer();
		if (lower != null && lower.getWebId().getValue()
				> range.getLowerBound().getWebId().getValue()) {
			range.setLowerBound(lower);
			return new DownPointingNodeState();
		}
		else {
			return new StandardNodeState();
		}
	}

	/**
	 * @return "Up Pointing Node State"
	 */
	public final String toString() {
		return "Up Pointing Node State";
	}
}
